//
//  KLHelp.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/21.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLHelp.h"
#import "sys/utsname.h"
#import "Reachability.h"
#import "UIAlertView+Blocks.h"
#import "HemaConst.h"
#import "Masonry.h"
#import "SSKeychain.h"

static UIImageView *iv;
static UILabel *noticeLabel;

@implementation KLHelp

//创建登陆按钮，传入按钮标题
+ (void)initButtton:(UIButton *)button withTitle:(NSString *)title {
    if (button == nil) {
        return;
    }
    
    UIImage *image  = [UIImage imageNamed:@"button_normal"];
    UIImage *image2 = [UIImage imageNamed:@"button_pressed"];
    UIImage *image3 = [UIImage imageNamed:@"button_focused"];
    UIImage *image4 = [UIImage imageNamed:@"button_disabled"];
    
    CGFloat top    = 15; // 顶端盖高度
    CGFloat bottom = 15; // 底端盖高度
    CGFloat left   = 15; // 左端盖宽度
    CGFloat right  = 15; // 右端盖宽度
    
    // UIImageResizingModeStretch：拉伸模式，通过拉伸UIEdgeInsets指定的矩形区域来填充图片
    // UIImageResizingModeTile：平铺模式，通过重复显示UIEdgeInsets指定的矩形区域来填充图片
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    
    image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    image2 = [image2 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    image3 = [image3 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    image4 = [image4 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setBackgroundImage:image2 forState:UIControlStateHighlighted];
    [button setBackgroundImage:image3 forState:UIControlStateSelected];
    [button setBackgroundImage:image4 forState:UIControlStateDisabled];
    
    button.titleLabel.font = [UIFont systemFontOfSize:16.];
    [button setTintColor:[UIColor whiteColor]];
    [button setTitle:title forState:UIControlStateNormal];
}

//导航栏美化
+ (void)setNavigationBarBgColor:(UIColor *)color controller:(UIViewController *)ctrl
{
    //设置导航栏背景及字体大小颜色
    ctrl.navigationController.navigationBar.barTintColor = color;
    [ctrl.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f], NSForegroundColorAttributeName: [UIColor whiteColor]}];
    ctrl.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //设置导航栏透明
    ctrl.navigationController.navigationBar.translucent = NO;
    
    //去掉下边黑线
    [ctrl.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    ctrl.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}

//警告框设置，传入的代码块传给警告框的action直接使用
+ (void)showAlertViewforViewController:(UIViewController *)viewController text:(NSString *)text dismissedOperate:(void (^)(void))dismissedOperate {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:text
                                                    message:nil
                                           cancelButtonItem:[RIButtonItem itemWithLabel:@"设置" action:dismissedOperate]
                                           otherButtonItems:[RIButtonItem itemWithLabel:@"好" action:nil], nil];
    [alert show];
}

//在控制器中显示圆形进度条
+ (void)showTextHUDforViewController:(UIViewController *)viewController text:(NSString *)text dismissedOperate:(void (^)(void))dismissedOperate {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:viewController.view animated:YES];//第三方框架圆形进度条的对象创建
    hud.completionBlock = dismissedOperate;
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelFont = [UIFont systemFontOfSize:15.0f];
    hud.detailsLabelText = text;
    hud.margin = 20.f;
    hud.removeFromSuperViewOnHide = YES;//隐藏时从父控件中移除
    
//    [hud hide:YES afterDelay:0.4f];
    [self creatCoverView:viewController.view];
}

//在视图中显示圆形进度条
+ (void)showTextHUDforView:(UIView *)view text:(NSString *)text dismissedOperate:(void (^)(void))dismissedOperate {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.completionBlock = dismissedOperate;
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelFont = [UIFont systemFontOfSize:15.0f];
    hud.detailsLabelText = text;
    hud.margin = 20.f;
    hud.removeFromSuperViewOnHide = YES;
    
//    [hud hide:YES afterDelay:10.0f];
//    [self creatCoverView:view];
}

+(MBProgressHUD *)showTextHUDforView:(UIView *)view text:(NSString *)text{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelFont = [UIFont systemFontOfSize:15.0f];
    hud.detailsLabelText = text;
    hud.margin = 20.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:2.f];
    return hud;
}

//圆形进度条创建
+ (MBProgressHUD*)showHUDAddedTo:(UIView*)view title:(NSString *)title details:(NSString *)details animated:(BOOL)animated {
    [MBProgressHUD hideAllHUDsForView:view animated:animated];
    [self creatCoverView:view];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    if (title && title.length > 0) {
        hud.labelText = title;
    }
    if (details && details.length) {
        hud.detailsLabelText = details;
    }
    [view addSubview:hud];
    [hud show:animated];
    return hud;
}

+ (MBProgressHUD*)showHUDAddedTo:(UIView*)view animated:(BOOL)animated {

    return [MBProgressHUD showHUDAddedTo:view animated:animated];
}

//圆形进度条隐藏
+ (void)hideAllHUDsForView:(UIView*)view animated:(BOOL)animated {
    
    [UIView animateWithDuration:0.4 // 动画时长
                     animations:^{
                         coverView.alpha = 0;
                     }];
    
    double delayInSeconds = 0.4;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [coverView removeFromSuperview];
    });
    [MBProgressHUD hideAllHUDsForView:view animated:animated];
}

//判断密码中是否包含特殊字符
+ (BOOL)haveSpecialChar:(NSString *)text {
    NSCharacterSet *nameCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"] invertedSet];
    NSRange userNameRange = [text rangeOfCharacterFromSet:nameCharacters];
    if (userNameRange.location != NSNotFound) {
        //        表示包含特殊字符
        return YES;
    }
    return NO;
}

//匹配机型和网络状态
+ (NSString*)deviceString {
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([deviceString isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([deviceString isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([deviceString isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([deviceString isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone7,1"]) return @"iPhone 6plus";
    if ([deviceString isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"]) return @"iPhone 6splus";
    if ([deviceString isEqualToString:@"iPhone3,2"]) return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPad1,1"])   return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])   return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])   return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])   return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"i386"])      return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])    return @"Simulator";
    
    return deviceString;
}

//字符编码长度(传入一个字符串，返回这个字符串变成ascii编码之后的总字符长度)
+(NSUInteger)unicodeLengthOfString:(NSString *)text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}

// 格式化时间戳(返回格式化的日期时间字符串,样式为时分秒 月日)
+ (NSString *)getTimeStringWithFormattor:(NSString *)formattor andTimeStamp:(NSTimeInterval)timeStamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:formattor]; // 设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制 @"HH:mm:ss MM/dd"
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timeStamp / 1000];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    return confromTimespStr;
}

// 判断当前的网络状况
+(BOOL)isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            break;
    }
    
    return isExistenceNetwork;
}

+(BOOL)systemDateFormateIs12_or_24{
    //获取系统是24小时制或者12小时制
    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
    NSRange containsA = [formatStringForHours rangeOfString:@"a"];
    BOOL hasAMPM = containsA.location != NSNotFound;
    //hasAMPM==TURE为12小时制，否则为24小时制
    return hasAMPM;
}

//创建蒙板
+(void)creatCoverView:(UIView *)fatherView{
    coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0.4;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:coverView];
//    [fatherView bringSubviewToFront:coverView];
}

//将字符串转字典
+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//将字典转字符串
+(NSString*)dictionaryToJson:(NSDictionary *)dic{
    if (dic == nil) {
        return nil;
    }
    
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//获取主体蓝色
+(UIColor *)mainBlueColor{
    return [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
}

//初始化导航栏
+(void)navSet:(UIViewController *)SELF doBackHandeler:(void (^)(UIButton *backButton))doBackHandler{
    [SELF.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:21]}];
    SELF.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    [SELF.navigationController.navigationBar setTranslucent:NO];
    
    //左侧返回按钮
    UIButton *backbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    SELF.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backbutton];
    
    doBackHandler(backbutton);
}

// 实名认证专用
/**设置导航条左边返回 右边下一步*/
+ (void)navSet:(UIViewController *)SELF doBackHandler:(void(^)(UIButton *backButton))doBackHandler nextStepHandler:(void(^)(UIButton *nextStepBtn)) nextStepHandler {
 
    [SELF.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:21]}];
    SELF.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    
    // 左侧返回按钮:建议创建button用遍历构造器方法
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backBtn.frame = CGRectMake(10, 0, 10, 20);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    SELF.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    doBackHandler(backBtn);
    
    // 右侧下一步按钮
    UIButton *nextStepBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    nextStepBtn.frame = CGRectMake(UI_View_Width - 60, 0, 60, 20);
    [nextStepBtn setTitle:@"下一步" forState:(UIControlStateNormal)];
//    [nextStepBtn setBackgroundColor:[UIColor greenColor]];
    [nextStepBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    SELF.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:nextStepBtn];
    nextStepHandler(nextStepBtn); //block 回调
}

/**免密管理初始化导航条*/
+ (void)navSetMianMi:(UIViewController *)SEFL doBackHandler:(void (^)(UIButton *backBtn))doBackHandler saveHandler:(void (^)(UIButton *saveBtn))saveHandler {
    [SEFL.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:21.0]}];
    SEFL.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    [SEFL.navigationController.navigationBar setTranslucent:YES];
    
    // 返回
    UIButton *doBackButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    doBackButton.frame = CGRectMake(10, 0, 10, 20);
    [doBackButton setImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    SEFL.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:doBackButton];
    doBackHandler(doBackButton);
    
    // 保存
    UIButton *saveButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [saveButton setTitle:@"保存" forState:(UIControlStateNormal)];
    saveButton.frame = CGRectMake(UI_View_Width -60, 0, 60, 20);
    SEFL.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    saveHandler(saveButton);
}

//创建无数据和无网时的图片
+(void)setNoDateImageWithView:(UIView *)view type:(NSInteger)type{
    [self removeImgViewAndNoticeLabel];
    iv = [[UIImageView alloc]init];
    if(type == 0){
        [iv setImage:[UIImage imageNamed:@"暂无数据"]];
    }else if(type == 1){
        [iv setImage:[UIImage imageNamed:@"无网图标"]];
    }
    [view addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view).with.offset(0);
        make.centerY.equalTo(view).with.offset(-150);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    
    noticeLabel = [[UILabel alloc]init];
    if(type == 0){
        noticeLabel.text = @"暂无数据";
    }else if(type == 1){
        noticeLabel.text = @"网络故障";
    }
    noticeLabel.textColor = [UIColor lightGrayColor];
    noticeLabel.alpha = 0.9;
    noticeLabel.font = [UIFont systemFontOfSize:15];
    [view addSubview:noticeLabel];
    [noticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view).with.offset(0);
        make.bottom.equalTo(iv).with.offset(23);
    }];
}

//移除无数据和无网时的图片
+(void)removeImgViewAndNoticeLabel{
    
    [iv removeFromSuperview];
//    iv = nil;

    [noticeLabel removeFromSuperview];
//    noticeLabel = nil;
}

//创建／取消黑色半透明蒙板
+(void)blackCoverViewShowAndHide:(UIView *)fatherView showOrHide:(BOOL)isShow{
    if(isShow){
        coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.3;
        [fatherView addSubview:coverView];
    }else{
        [coverView removeFromSuperview];
    }
}

//比较两个年月日日期的大小
+(int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSLog(@"dates %@, %@", dt1, dt2);
    NSComparisonResult result = [dt1 compare:dt2];
    NSLog(@"result:%ld",(long)result);
    //后面的大是1，前面的大是－1
    return (int)result;
}

//获取用户的AESKEY
+(NSString *)getUserSixTeenRandomAESKey{
    //为每个用户创建一个aes密钥
    NSMutableString *randomStr = [NSMutableString string];
    for (int i = 0; i < 16; i++) {
        int x = arc4random() % 10;
        [randomStr appendString:[NSString stringWithFormat:@"%d",x]];
    }
    NSLog(@"用户的aesKey为:%@",randomStr);
    
//    return @"1111111111111111";
    return randomStr;
}

//获取锁对应公钥
+(NSString *)getLockRSAPublicKeyWithLockName:(NSString *)lockName{
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    NSString *codeStr = [publicKeysDic objectForKey:lockName];
    
    return codeStr;
}

//手机号转用户id
+(NSString *)userIDToTwelveByteWithUserID:(NSString *)userID{
    NSInteger length = userID.length;
    NSMutableString *userLongString = [NSMutableString string];
    for (int i = 0; i < 12 - length; i++) {
        [userLongString appendString:@"0"];
    }
    [userLongString appendString:userID];
    
    NSString *userIDString = [NSString stringWithFormat:@"%@",userLongString];
    return userIDString;
}

+ (BOOL)isIdentityStringIegal:(NSString *)identityString{
    
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

// 检验是不是6位纯数字
+ (BOOL)isSixdigitNumberString:(NSString *)pwdString {
    if (pwdString.length != 6) {return NO;}
    
    // 正则表达式
    NSString *regualStr = @"^[0-9]{6}$";
    
    NSPredicate *pwdStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regualStr];
    if ([pwdStringPredicate evaluateWithObject:pwdString]) {
        return YES;
    }else {
        return NO;
    }
}

/**数组转json*/
+ (NSString *)jsonFromArray:(NSArray *)array {
    
    if (array.count) {
        NSError *err = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&err];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else {
        return nil;
    }
   
}
@end
